package com.tucy.logistics.utils;

import com.tucy.logistics.common.constants.BaseConstants;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Locale;

/**
 * author: tcy
 * createDate: 2023/3/17
 * description: 汉语转拼音工具类
 */
public class PinYinUtil {

    public static String getFirstLetters(String chineseLan) {

        // 将汉字转换为字符数组
        char[] charChineseLan = chineseLan.toCharArray();

        // 定义输出格式
        HanyuPinyinOutputFormat hpFormat = new HanyuPinyinOutputFormat();

        // 小写格式输出
        hpFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);

        // 不需要语调输出
        hpFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        try {
            char first = charChineseLan[0];
            if (String.valueOf(first).matches(BaseConstants.IS_chinese)){
                return PinyinHelper.toHanyuPinyinStringArray(first, hpFormat)[0].substring(0,1);
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toPinYin(String chineseLan) {

        StringBuilder result = new StringBuilder();

        // 将汉字转换为字符数组
        char[] charChineseLan = chineseLan.toCharArray();

        // 定义输出格式
        HanyuPinyinOutputFormat hpFormat = new HanyuPinyinOutputFormat();

        // 小写格式输出
        hpFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);

        // 不需要语调输出
        hpFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        try {
            for (int i = 0; i < charChineseLan.length; i++) {
                char chinese = charChineseLan[i];
                if (String.valueOf(chinese).matches(BaseConstants.IS_chinese)){
                    String initial = PinyinHelper.toHanyuPinyinStringArray(chinese, hpFormat)[0];
                    result.append(initial);
                } else {
                    result.append(chinese);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}
